﻿using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Validation;

namespace PraiseSystem.Models
{
    public class User
    {
        [Required(ErrorMessage = "Please enter your ID")]
        [RegularExpression("P[0-9]{7}",ErrorMessage ="Please enter a valid ID")]
        public string UserID { get; set; }

        public virtual ICollection<Praise> Praises { get; set; }

        [Required(ErrorMessage = "Please enter your Name")]
        public string Name { get; set; }

        [Required(ErrorMessage ="Please enter your Email")]
        [RegularExpression(".+\\@microsoft\\.com", ErrorMessage = "Please enter a valid email")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter your phone")]
        [RegularExpression("[0-9]{11}", ErrorMessage = "Please enter a valid Phone")]
        public string Phone { get; set; }

        [Required(ErrorMessage = "Please enter your password")]
        public string PassWord { get; set; }

        public string ProfilePath { get; set; }
        public bool LeaveFlag { get; set; }

    }

    public class UserMap : EntityTypeConfiguration<User>
    {
        public UserMap()
        {
            ToTable("tb_User");
            HasKey(u => u.UserID);
            Property(p => p.UserID).HasMaxLength(10);
            Property(p => p.Name).IsRequired().HasMaxLength(10);
            HasMany(u => u.Praises).WithRequired(p => p.Owner).HasForeignKey(p => p.OwnerID);
        }
    }

    public class PraiserRepository
    {
        private static PraiseDBContext db;
        static PraiserRepository()
        {
            db = new PraiseDBContext();
        }

        public void AddUser(string id, string name, string profile = "", bool leaveFlag = false)
        {
            try
            {
                db.Users.Add(new User() { UserID = id, LeaveFlag = leaveFlag, Name = name, ProfilePath = profile, Email = "123@microsoft.com", Phone = "12345678954" });
                db.Receivers.Add(new Receiver() { ReceiverID = id, Name = name });
                db.SaveChanges();
            }
            catch (DbEntityValidationException dbex)
            {
                
            }
           
        }

        /// <summary>
        /// To get Praisers through id, if id is empty then get all praisers.
        /// </summary>
        /// <param name="id">PID</param>
        /// <returns></returns>
        public IEnumerable<User> GetUsers(string id = "")
        {
            return db.Users.Where(u => u.UserID == id||string.IsNullOrEmpty(id));
        }

        public IEnumerable<DateTime> TestDate()
        {
            return db.Users.Select(u => u.Praises.FirstOrDefault().PraiseDate);
        }

        
    }
}
